﻿using Microsoft.AspNetCore.Mvc;
using PLCS.Domain.Stations;
using PLCS.Domain.Tasks;
using PLCS.Domain.Trays;
using PLCS.SocialHttpApi.Attributes;
using PLCS.SocialHttpApi.Models;
using System.ComponentModel;
using Volo.Abp.AspNetCore.Mvc;

namespace PLCS.SocialHttpApi.Controllers;

[Route("api/[controller]/[action]")]
[ApiController]
[ServiceFilter(typeof(LogActionFilter))]
public class MESController : AbpControllerBase
{
    private readonly TaskManager _taskManager;
    private readonly IStationRepository _stationRepository;
    private readonly ITrayRepository _trayRepository;

    public MESController(TaskManager taskManager, IStationRepository stationRepository, ITrayRepository trayRepository)
    {
        _taskManager = taskManager;
        _stationRepository = stationRepository;
        _trayRepository = trayRepository;
    }

    [HttpPost]
    [Description("MES给PLCS下发任务")]
    [Requester("MES")]
    public async Task<Response_Mes> mes_to_plcs_task_release(Request_Mes_task_release request)
    {
        string seqNo = request.header.seqNo;
        var model = request.body;

        var startStation = await _stationRepository.GetStationByNumAsync(model.StartPos);
        var endStation = await _stationRepository.GetStationByNumAsync(model.EndPos);
        if (startStation == null)
            return new Response_Mes(new ResponseHeader("E", seqNo, "起始位不存在"));
        if (endStation == null)
            return new Response_Mes(new ResponseHeader("E", seqNo, "目标位不存在"));
        var task = new TaskModel(0, model.Level, model.StartPos, model.EndPos, null, Domain.Shared.Tasks.TaskType.普通流转, "MES下发", null, model.OrderNo);
        await _taskManager.InsertAsync(task);
        return new Response_Mes(new ResponseHeader("S", seqNo, ""));
    }

    [HttpPost]
    [Description("MES给PLCS下发配炉单")]
    [Requester("MES")]
    public async Task<Response_Mes> mes_to_plcs_stoveorder_release(Request_Mes_stoveorder_release request)
    {
        string seqNo = request.header.seqNo;
        var model = request.body;

        var targetStation = await _stationRepository.GetStationByNumAsync(model.EqNo);
        if (targetStation == null)
            return new Response_Mes(new ResponseHeader("E", seqNo, "目标设备不存在"));

        if (model.itemInfo == null || !model.itemInfo.Any())
            return new Response_Mes(new ResponseHeader("E", seqNo, "炉内明细不可为空"));

        foreach (var item in model.itemInfo)
        {
            var station = (await _trayRepository.GetTrayByNoAsync(item.TrayNo))?.Station?.StaNum;
            if (!string.IsNullOrEmpty(station))
            {
                var task = new TaskModel(0, 0, station, targetStation.StaNum, null, Domain.Shared.Tasks.TaskType.普通流转, "MES下发配炉单任务", null);
                await _taskManager.InsertAsync(task);
            }
        }

        return new Response_Mes(new ResponseHeader("S", seqNo, ""));
    }
}